//
//  NetworkTools.m
//  新浪微博OC
//
//  Created by  justinchou on 16/3/7.
//  Copyright © 2016年  justinchou. All rights reserved.
//

#import "NetworkTools.h"
#import "AFHTTPSessionManager.h"

@implementation NetworkTools
/// 创建单例
///
/// @return 返回一个单例
+ (instancetype)sharedTools{
    static NetworkTools *instance;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[NetworkTools alloc] initWithBaseURL:nil];
        //添加能够支持的数据类型
        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
    });
    
    return instance;
}

//自己封装AFNetworking框架
- (void)request:(JustinRequestMethod)method
      URLString:(NSString *)urlString
     parameters:(NSDictionary *)params
       finished:(void (^)(id result))finished {
    
    if (method == GET) {
        
        [self GET:urlString parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (responseObject != nil) {
                finished(responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (error != nil) {
                finished(error);
            }
        }];
    } else {
        
        [self POST:urlString parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (responseObject != nil) {
                finished(responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (error != nil) {
                NSLog(@"%@", error);
                finished(nil);
            }
        }];
    }
    
}

@end
